import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware, TokenPayload, verifyToken } from '@/utils/auth';
import UserModel from '@/models/user';
import { query } from '@/utils/db';
import { RowDataPacket } from 'mysql2/promise';

export async function GET(request: NextRequest) {
  console.log('=== 检查登录状态API请求开始处理 ===');
  console.log('请求URL:', request.url);
  
  // 不打印整个头信息，仅记录是否包含授权信息
  const hasAuthHeader = request.headers.has('Authorization') || request.headers.has('authorization');
  console.log('包含授权头:', hasAuthHeader);

  try {
    // 直接从请求中获取token并验证，避免中间环节出错
    const authHeader = request.headers.get('Authorization') || request.headers.get('authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      console.log('授权头不存在或格式不正确');
      return NextResponse.json(
        {
          authenticated: false,
          message: '未提供有效的授权信息'
        },
        { status: 401 }
      );
    }

    const token = authHeader.substring(7); // 去除"Bearer "前缀
    if (!token || token.length < 10) { // 简单验证token长度
      console.log('令牌不存在或长度异常:', token ? token.length : 0);
      return NextResponse.json(
        {
          authenticated: false,
          message: '无效的授权令牌'
        },
        { status: 401 }
      );
    }

    console.log('获取到令牌，长度:', token.length);

    // 验证token
    const decoded = verifyToken(token);
    if (!decoded || !decoded.id) {
      console.log('令牌验证失败或缺少用户ID');
      return NextResponse.json(
        {
          authenticated: false,
          message: '令牌无效或已过期'
        },
        { status: 401 }
      );
    }

    const userId = decoded.id;
    console.log('令牌验证成功，用户ID:', userId);

    // 从数据库中获取用户信息
    try {
      // 直接使用query函数查询用户，避免可能的Model层问题
      const userQuery = `
        SELECT 
          u.id, 
          u.username, 
          u.email,
          u.avatar,
          u.is_company_admin,
          c.id as company_id,
          c.name as company_name,
          c.industry as company_industry
        FROM users u
        LEFT JOIN companies c ON u.id = c.admin_user_id
        WHERE u.id = ?
      `;
      
      console.log('执行SQL查询用户信息:', userQuery);
      console.log('查询参数:', userId);
      
      const [userResults] = await query<RowDataPacket[]>(userQuery, [userId]);
      
      if (!userResults || userResults.length === 0) {
        console.log('未找到用户，ID:', userId);
        return NextResponse.json(
          {
            authenticated: false,
            message: '找不到用户信息'
          },
          { status: 404 }
        );
      }

      // 获取用户信息
      const userResult = userResults[0];
      console.log('成功获取用户信息:', JSON.stringify({
        id: userResult.id,
        username: userResult.username,
        email: userResult.email ? `${userResult.email.substring(0, 3)}...` : null,
        is_company_admin: userResult.is_company_admin,
        company_id: userResult.company_id
      }));

      // 构建返回的用户信息对象
      const user = {
        id: userResult.id,
        username: userResult.username,
        email: userResult.email,
        avatar: userResult.avatar,
        is_company_admin: Boolean(userResult.is_company_admin),
        company_id: userResult.company_id,
        company_name: userResult.company_name,
        company_industry: userResult.company_industry
      };

      console.log('用户验证成功，返回用户信息');
      return NextResponse.json(
        {
          authenticated: true,
          message: '已登录',
          user
        },
        { status: 200 }
      );
    } catch (dbError) {
      console.error('数据库查询用户信息出错:', dbError);
      return NextResponse.json(
        {
          authenticated: false,
          message: '获取用户信息失败',
          error: `数据库查询错误: ${(dbError as Error).message}`
        },
        { status: 500 }
      );
    }
  } catch (error) {
    console.error('检查登录状态过程中发生错误:', error);
    return NextResponse.json(
      {
        authenticated: false,
        message: '验证用户身份时出错',
        error: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    );
  }
}
